<template>
  <!-- 导航栏组件 -->
  <custom-navbar></custom-navbar>
  <!-- refresher-enabled 开启下拉刷新 -->
  <!-- @refresherrefresh 自定义下拉刷新被触发 -->
  <!-- refresher-triggered 设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发 -->
  <scroll-view scroll-y class="scrollView" @scrolltolower="onScrolltolower" refresher-enabled
    @refresherrefresh="onRefresherrefresh" :refresher-triggered="isTriggered">
    <!-- 导入骨架屏组件 -->
    <homeSkeleton v-if="isLoading"></homeSkeleton>
    <template v-else>
      <!-- 轮播图组件 自动导入 -->
      <XtxSwiper :list="bannerList"></XtxSwiper>
      <!-- 前台分类 -->
      <category-panel :categoryList="categoryList"></category-panel>
      <!-- 热门推荐 -->
      <hot-panel :hotPanelList="hotPanelList"></hot-panel>
      <!-- 猜你喜欢 自动导入 -->
      <XtxGuess ref="xtxGuessRef"></XtxGuess>
    </template>
  </scroll-view>
</template>

<script setup lang="ts">
import homeSkeleton from '@/pages/index/components/homeSkeleton.vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHotMutliListAPI } from '@/apis/home';
import CustomNavbar from './components/CustomNavbar.vue';
import CategoryPanel from './components/CategoryPanel.vue';
import HotPanel from './components/HotPanel.vue';
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app';
import type { BannerItem, categoryItem, hotPanelItem } from '@/types/home';

// 存放图片数据
const bannerList = ref<BannerItem[]>([])
// 发请求获取广告图片
const getHomeBannerList = async () => {
  const res = await getHomeBannerAPI()
  // console.log(res)
  bannerList.value = res.result
}

// 保存前台分类数据
const categoryList = ref<categoryItem[]>([])
// 发送请求获取前台分类
const getHomeCategoryList = async () => {
  const res = await getHomeCategoryAPI()
  // console.log(res, 27272727)
  categoryList.value = res.result
}

// 保存热门推荐数据
const hotPanelList = ref<hotPanelItem[]>([])
// 发请求获取热门推荐数据
const getHotMutliList = async () => {
  const res = await getHotMutliListAPI()
  // console.log(res, 44444)
  hotPanelList.value = res.result
}

// 引入组合式函数 实现滚动刷新效果
import { useMouse } from '@/componables/index'
const { guessRef: xtxGuessRef, onScrolltolower } = useMouse()

// 控制下拉刷新的状态
const isTriggered = ref(false)
// 下拉刷新
const onRefresherrefresh = async () => {
  // console.log('下拉刷新')
  isTriggered.value = true
  // Promise.all([]) 将异步请求变得同步
  await Promise.all([
    getHomeBannerList(),
    getHomeCategoryList(),
    getHotMutliList(),
    xtxGuessRef.value?.setData()
  ])
  isTriggered.value = false
}

// 骨架屏显示与隐藏
const isLoading = ref(false)

onLoad(async () => {
  // 没有数据时显示骨架屏
  isLoading.value = true
  await Promise.all([
    getHomeBannerList(),
    getHomeCategoryList(),
    getHotMutliList()
  ])
  // 获取到数据隐藏骨架屏
  isLoading.value = false
})


</script>

<style lang="scss">
page {
  background-color: #F7F7F7;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.scrollView {
  flex: 1;
  overflow: hidden;
}
</style>
